<template>
  <div>
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        background="#3296fa"
        @clear="isResultShow = false"
        @input="inputHandler"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText"></search-result>
    <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText" :searchText="searchText" @search-event="onSearchHandler"></search-suggestion>
    <!-- 搜索历史记录 -->
    <search-history v-else :searchHistorys="searchHistorys" @delete-history="searchHistorys = []" @search="onSearch"></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { getItem, setItem } from '@/utils/storage'
const TOUTIAO_SEARCH_HISTORY = 'TOUTIAO_SEARCH_HISTORY'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false, // 控制搜索结果的展示
      searchHistorys: getItem(TOUTIAO_SEARCH_HISTORY) || [] // 搜索历史
    }
  },
  watch: {
    searchHistorys (val) {
      setItem(TOUTIAO_SEARCH_HISTORY, val)
    }
  },
  methods: {
    onSearch (val) {
      // console.log(val)
      this.searchText = val
      this.isResultShow = true
      var index = this.searchHistorys.indexOf(val)
      if (index !== -1) {
        this.searchHistorys.splice(index, 1)
      }
      this.searchHistorys.unshift(val)
      console.log(this.searchHistorys)
    },
    onSearchHandler (str) {
      this.isResultShow = true
      this.searchText = str
    },
    // 输入框没有内容默认显示搜索历史记录
    inputHandler () {
      if (this.searchText.length === 0) {
        this.isResultShow = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.van-search__action {
  color: #fff;
}
.van-search {
  position: fixed;
  z-index: 1;
  width: 100vw;
}
.search-result,
.search-history,
.search-suggestion {
  padding-top: 108px;
}
</style>
